const connection = require('../app/database')

class CommentService {
  async create(momentId, content, userId) {
    try {
      const statement = `INSERT INTO comment (content, moment_id, user_id) VALUES (?, ?, ?);`;
      `INSERT INTO comment SET ?`
      const [result] = await connection.execute(statement, [content, momentId, userId]);
      return result;
    } catch (e) {
      console.log(e)
    }
  }

  async reply(momentId, content, userId, commentId) {
    try {
      const statement = `INSERT INTO comment (content, moment_id, user_id, comment_id) VALUES (?, ?, ?, ?);`;
      `INSERT INTO comment SET ?`
      const [result] = await connection.execute(statement, [content, momentId, userId, commentId]);
      return result;
    } catch (e) {
      console.log(e)
    }
  }

  async update(content, commentId) {
    try {
      const statement = `UPDATE comment SET content = ? WHERE id = ?`;
      const [result] = await connection.execute(statement, [content, commentId]);
      return result;
    } catch (e) {
      console.log(e)
    }
  }

  async remove(commentId){
    console.log(commentId);
    const statement = `DELETE FROM comment WHERE id = ?`;
    const [result] = await connection.execute(statement, [commentId]);
    return result;
  }

  async list(momentId){
    const statement = `
     SELECT 
        m.id mid,m.content mcontent,m.createAt mcreateAt,m.updateAt mupadateAt,
        JSON_OBJECT('id',u.id,'name',u.name) author,
        JSON_ARRAYAGG(
            JSON_OBJECT('id',c.id,'content',c.content,'createAt',c.createAt,'updateAt',c.updateAt,
                'user',JSON_OBJECT('id',cu.id,'name',cu.name))
        ) comments
     FROM moment m
     LEFT JOIN user u ON m.user_id = u.id
     LEFT JOIN comment c ON c.moment_id = m.id
     LEFT JOIN user cu ON c.user_id = cu.id
     WHERE moment_id = ?
    `
    const [result] = await connection.execute(statement,[momentId])
    return result
  }
}

module.exports = new CommentService();